import path from 'path'
import Sequelize from 'sequelize'
import fileStreamRotator from 'file-stream-rotator'
import logSequelize from '../utils/log'
import dbConfig from '../config/dbConfig'
import commonConfig from '../config/commonConfig'

const { logDirectory, isDev, env } = commonConfig
const { database, username, password, host, dialect } = dbConfig[env]

const { Op } = Sequelize
const operatorsAliases = {
  $eq: Op.eq,
  $ne: Op.ne,
  $gte: Op.gte,
  $gt: Op.gt,
  $lte: Op.lte,
  $lt: Op.lt,
  $not: Op.not,
  $in: Op.in,
  $notIn: Op.notIn,
  $is: Op.is,
  $like: Op.like,
  $notLike: Op.notLike,
  $iLike: Op.iLike,
  $notILike: Op.notILike,
  $regexp: Op.regexp,
  $notRegexp: Op.notRegexp,
  $iRegexp: Op.iRegexp,
  $notIRegexp: Op.notIRegexp,
  $between: Op.between,
  $notBetween: Op.notBetween,
  $overlap: Op.overlap,
  $contains: Op.contains,
  $contained: Op.contained,
  $adjacent: Op.adjacent,
  $strictLeft: Op.strictLeft,
  $strictRight: Op.strictRight,
  $noExtendRight: Op.noExtendRight,
  $noExtendLeft: Op.noExtendLeft,
  $and: Op.and,
  $or: Op.or,
  $any: Op.any,
  $all: Op.all,
  $values: Op.values,
  $col: Op.col
}

const sequelize = new Sequelize(database, username, password, {
  host,
  dialect,
  timezone: '+08:00',
  pool: {
    max: 5,
    idle: 10000
  },
  define: {
    charset: 'utf8',
    dialectOptions: {
      collate: 'utf8_general_ci'
    },
    timestamps: false
  },
  logging: logSequelize({
    stream:
      !isDev &&
      fileStreamRotator.getStream({
        date_format: 'YYYYMMDD',
        filename: path.join(logDirectory, 'sql-%DATE%.log'),
        frequency: 'daily',
        verbose: false
      })
  }),
  operatorsAliases
})

export default sequelize
